
package com.myWeb.listener;

import com.myWeb.util.JdbcUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class OneListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {

        JdbcUtil util = new JdbcUtil();
        Map map = new HashMap();
        try{
            for(int i=0; i<20; i++){
                Connection conn = util.getConnection();
                System.out.println("服务器启动时，创建连接对象");
                map.put(conn,true);
            }
            ServletContext application = sce.getServletContext();
            application.setAttribute("key1",map);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

        ServletContext application = sce.getServletContext();
        Map map = (Map)application.getAttribute("key1");
        Iterator it = map.keySet().iterator();
        while(it.hasNext()){
            Connection conn = (Connection)it.next();
            if(null != conn){
                System.out.println(conn + "被销毁");
            }

        }
    }
}

